<template>
  <div style="width: 100%">
    <el-dialog destroy-on-close :append-to-body="true" :visible.sync="visible" title="属性定义" width="1000px">
      <el-form v-if="visible" :disabled="dialogType==='view'" ref="form" :model="formData" :rules="rules"
               size="small" label-width="110px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="中文名称" prop="nameCn">
              <el-input v-model="formData.nameCn"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="编码标识" prop="columnName">
              <el-input :disabled="dialogType!=='add'" v-model="formData.columnName"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="属性分类" prop="attributeTypeId">
              <el-select style="width: 99%" v-model="formData.attributeTypeId"
                         @change="setAttributeType">
                <template v-for="item in attributeTypeList">
                  <el-option :label="item.nameCn" :value="item.oid"></el-option>
                </template>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="属性值" prop="codeTypeId"
                          v-if="attributeObj&&['single_choice','multiple_choice'].includes(attributeObj.name)">
              <el-select style="width: 99%" v-model="formData.codeTypeId">
                <template v-for="{nameCn,oid} in enumList">
                  <el-option :label="nameCn" :value="oid"></el-option>
                </template>
              </el-select>
            </el-form-item>
            <el-form-item label="属性值" prop="typeName"
                          v-if="attributeObj&&['single_choice_reference','multiple_choice_reference'].includes(attributeObj.name)">
              <el-select-tree :value.sync="formData.typeName"
                              :options="parentIdList"></el-select-tree>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row v-show="false" v-if="attributeObj&&['decimal','string','number'].includes(attributeObj.columnType)">
          <el-col :span="12">
            <el-form-item label="长度">
              <el-input-number style="width: 100%" :min="1" :max="attributeObj.length"
                               v-model="formData.length=attributeObj.length"></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="attributeObj&&attributeObj.columnType==='decimal'">
            <el-form-item label="精度">
              <el-input-number style="width: 100%" :min="0" :max="attributeObj.accuracy"
                               v-model="formData.accuracy"></el-input-number>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="英文名称" prop="nameEn">
              <el-input v-model="formData.nameEn"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="属性类型">
              <el-select disabled style="width: 99%" v-model="formData.attributeType">
                <template v-for="item in columnTypeList">
                  <el-option :label="item.name" :value="item.type"></el-option>
                </template>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item label="英文描述">
              <el-input v-model="formData.describeEn"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item label="中文描述" prop="describeCn">
              <el-input v-model="formData.describeCn"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="是否必填" prop="required">
              <el-radio-group v-model="formData.required">
                <el-radio :label="0">否</el-radio>
                <el-radio :label="1">是</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="默认值">
              <el-input v-model="formData.columnDefault"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="单位组">
              <el-select style="width: 100%" v-model="formData.unitGroup" @change="getUnitData">
                <template v-for="{oid,nameCn} in unitGroupData">
                  <el-option :value="oid" :label="nameCn"></el-option>
                </template>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="默认单位">
              <el-select style="width: 100%" v-model="formData.unit">
                <template v-for="{name,oid} in unitData">
                  <el-option :value="oid" :label="name"></el-option>
                </template>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="密级" prop="secret">
              <el-select style="width: 100%" v-model="formData.secret">
                <template v-for="{name,value} in secretData">
                  <el-option :label="name" :value="value"></el-option>
                </template>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否动态属性" prop="dynamicFlag">
              <el-select style="width: 100%" v-model="formData.dynamicFlag"
                         :disabled="disabledAttr.includes('dynamicFlag')">
                <el-option label="是" :value="1"></el-option>
                <el-option label="否" :value="0"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <div slot="footer" style="text-align: center;height: 36px">
        <el-button size="medium" type="primary" v-if="dialogType!=='view'" @click="save">保存</el-button>
        <el-button size="medium" @click="visible=false">取消</el-button>
      </div>
    </el-dialog>

    <get-data-common-dialog title="选择枚举"
                            :limit="1"
                            :column="EnumManageOption.column"
                            url="/api/manager-api/mx-code-type/query"
                            @addToList="addToList"
                            ref="gdcd">
    </get-data-common-dialog>
  </div>
</template>

<script>
import * as attribute from "@/api/modulManage/attribute"
import * as common from "@/api/common";
import GetDataCommonDialog from "@/views/DMDComponent/getDataCommonDialog.vue";
import PropertiesDefinedTemp from "@/views/DMDPropertiesDefined/PropertiesDefinedTemp.vue";
import ElSelectTree from "@/components/el-select-tree.vue";
import {request} from "axios";
import * as api from "@/api/modulManage/entity";
import {getColumnType} from "@/api/modulManage/attributeClassify";

export default {
  name: "addProperties",
  components: {ElSelectTree, PropertiesDefinedTemp, GetDataCommonDialog},
  inject: ["EnumManageOption"],
  props: {
    defaultValue: {
      type: Object,
      default: () => {
        return {}
      }
    },
    disabledAttr: {
      type: Array,
      default: () => {
        return []
      }
    },
  },
  data() {
    return {
      visible: false,
      activeName: ["1", "2"],
      formData: {
        nameCn: "",
        nameEn: "",
        attributeType: "",
        typeName: "",
        columnName: "",
        describeEn: "",
        describeCn: "",
        required: 0,
        columnDefault: "",
        unitGroup: "",
        unit: "",
        attributeTypeId: "",
        codeTypeId: "",
        secret: "",
        dynamicFlag: "",
        length: 1,
        accuracy: 0,
      },
      baseRules: {
        nameCn: [{required: true, message: "请输入中文名称", trigger: "blur"}],
        nameEn: [
          {pattern: '^[A-Za-z][A-Za-z0-9_]{1,29}$', message: '请输入正确英文名称'}
        ],
        columnName: [
          {required: true, message: "请输入编码标识", trigger: "blur"},
          {pattern: '^[A-Za-z][A-Za-z0-9_]{1,29}$', message: '请输入正确编码标识'}
        ],
        attributeTypeId: [{required: true, message: "请选择属性分类", trigger: "change"}],
        describeCn: [{required: true, message: "请输入中文描述", trigger: "blur"}],
        required: [{required: true, message: "请选择是否必填", trigger: "change"}],
        dynamicFlag: [{required: true, message: "请选择是否动态属性", trigger: "change"}],
        secret: [{required: true, message: "请选择密级", trigger: "change"}],
      },
      rules_1: {
        codeTypeId: [{required: true, message: "请选择属性值", trigger: "change"}],
      },
      rules_2: {
        typeName: [{required: true, message: "请选择属性值", trigger: "change"}],
      },

      data: [],
      loading: false,
      option: {
        height: '300px',
        calcHeight: 30,
        dialogWidth: 900,
        tip: false,
        searchShow: true,
        searchMenuSpan: 6,
        border: true,
        index: false,
        selection: true,
        labelWidth: 120,
        menuWidth: 200,
        viewBtn: false,
        dialogClickModal: false,
        tabs: true,
        delBtn: false,
        addBtn: false,
        editBtn: false,
        refreshBtn: false,
        columnBtn: false,
        align: "center",
        menu: false,
        column: [
          {
            label: '中文名称',
            prop: 'name',
          },
          {
            label: "英文名称",
            prop: "nameEn",
          },
          {
            label: "枚举值",
            prop: "value",
          }
        ]
      },

      attributeTypeList: [],
      propertiesSelection: [],
      dialogType: "add",

      unitGroupData: [],
      unitData: [],
      secretData: [],

      enumList: [],
      parentIdList: [],
    }
  },
  computed: {
    attributeObj() {
      if (this.attributeTypeList && this.attributeTypeList.length > 0) {
        let ids = this.attributeTypeList.map(i => i.oid);
        let index = ids.indexOf(this.formData.attributeTypeId);
        return this.attributeTypeList[index];
      }
      return false;
    },
    rules() {
      this.formData.length = 1;
      this.formData.accuracy = 0;
      if (this.attributeObj && ['single_choice', 'multiple_choice'].includes(this.attributeObj.name)) {
        this.formData.typeName = ""
        return {...this.baseRules, ...this.rules_1}
      }
      if (this.attributeObj && ['single_choice_reference', 'multiple_choice_reference'].includes(this.attributeObj.name)) {
        this.formData.codeTypeId = ""
        return {...this.baseRules, ...this.rules_2}
      }
      this.formData.codeTypeId = ""
      this.formData.typeName = ""
      return this.baseRules;
    }
  },
  methods: {
    remove() {
      let data = this.deepCopy(this.propertiesSelection).map(item => item.oid);
      let properties = this.deepCopy(this.data);
      this.data = [];
      properties.forEach(item => {
        if (!data.includes(item.oid)) {
          this.data.push(item);
        }
      })
    },
    addToList(list) {
      let properties = this.deepCopy(this.data);
      this.data = [];
      if (properties.length > 0) {

        let ids = properties.map(item => item.oid ? item.oid : -1);
        list.forEach(item => {
          if (ids.length > 0 && item.oid && !ids.includes(item.oid)) {
            properties.push(item);
          }
        })
      } else {
        properties.push(...list);
      }

      this.$nextTick(() => {
        this.data = properties;
        this.$refs['gdcd'].close();
      })
    },

    save() {
      let method = this.dialogType === "add" ? "addAttribute" : "updateAttribute";
      this.$refs["form"].validate(f => {
        if (f) {
          this.formData.codeTypeId = this.data.length !== 0 ? this.data[0].oid : "";
          attribute[method](this.formData).then((res) => {
            this.$emit("addToList", [res.data.data]);
          })
        }
      })
    },

    resetDialog() {
      this.formData = {
        nameCn: "",
        nameEn: "",
        attributeType: "",
        typeName: "",
        columnName: "",
        describeEn: "",
        describeCn: "",
        required: 0,
        columnDefault: "",
        unitGroup: "",
        unit: "",
        attributeTypeId: "",
        codeTypeId: "",
        secret: "",
        dynamicFlag: "",
        length: 1,
        accuracy: 0,
        ...this.defaultValue
      }
    },
    setAttributeType(v) {
      this.attributeTypeList.forEach(item => {
        if (item.oid === v) {
          this.formData.attributeType = item.columnType;
          this.formData.attributeTypeId = item.oid;
        }
      })
    },
    getAttributeType() {
      attribute.getAttribute().then(res => {
        this.attributeTypeList = res.data.data;
      })
    },

    details(row) {
      attribute.getDetail({oid: row.oid}).then(res => {
        Object.assign(this.formData, res.data.data);
        this.visible = true;
      })
    },
    getUnitGroupData() {
      common.getUnitGroup().then(res => {
        this.unitGroupData = res.data.data;
      })
    },
    getUnitData(oid) {
      this.formData.unit = "";
      common.getUnit({oid}).then(res => {
        this.unitData = res.data.data;
      })
    },
    getSecret() {
      common.getDic("secret").then(res => {
        this.secretData = res.data.data;
      })
    },

    edit(row) {
      this.dialogType = "edit";
      this.details(row);
    },

    view(row) {
      this.dialogType = "view";
      this.details(row);
    },

    open() {
      this.dialogType = "add";
      this.resetDialog();
      this.visible = true;
    },
    close() {
      this.visible = false;
    },
    getEnumList() {
      request({url: "/api/manager-api/mx-code-type/list", method: "get"}).then(res => {
        this.enumList = res.data.data;
      })
    },
    getEntityList() {
      api.getEntity().then(res => {
        this.parentIdList = res.data.data;
      })
    },
    getColumnType() {
      getColumnType().then(res => {
        this.columnTypeList = res.data.data;
      })
    },
  },
  mounted() {
    this.getAttributeType();
    this.getUnitGroupData();
    this.getSecret();
    this.getEnumList();
    this.getEntityList();
    this.getColumnType();
  },
  watch: {
    dialogType: {
      handler(v) {
        let state = ["add", "edit"].includes(v)
        this.option.selection = state;
        this.option.header = state;
      },
      immediate: true,
      deep: true
    }
  }
}
</script>

<style scoped lang="scss">
$mdBtns: 36px;
.md-component-btns {
  height: $mdBtns;
  width: calc(100% - 20px);
  position: absolute;
  bottom: 20px;
  text-align: center;
}
</style>
